<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <view class="nav-bar transparent">
      <view class="nav-content">
        <text class="nav-title">个人中心</text>
      </view>
    </view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <scroll-view 
        scroll-y 
        class="profile-scroll"
      >
        <!-- 用户信息卡片 -->
        <view class="user-card">
          <view class="user-info">
            <view class="avatar-wrapper" @click="showAvatarOptions">
              <image 
                :src="userStore.userInfo?.avatar || '/static/default-avatar.png'" 
                mode="aspectFill"
                class="user-avatar"
              />
              <view class="avatar-edit">
                <text class="edit-icon">✏️</text>
              </view>
            </view>
            
            <view class="user-details">
              <text class="user-name" @click="editProfile">{{ userStore.userInfo?.username || '用户' }}</text>
              <text class="user-email">{{ userStore.userInfo?.email || '未设置邮箱' }}</text>
              <text class="join-date">{{ formatJoinDate(userStore.userInfo?.createdAt) }}</text>
            </view>
          </view>
          
          <!-- 统计数据 -->
          <view class="stats-container">
            <view class="stat-item" @click="goToDiaryList">
              <text class="stat-number">{{ userStore.userInfo?.diaryCount || 0 }}</text>
              <text class="stat-label">日记</text>
            </view>
            <view class="stat-divider"></view>
            <view class="stat-item" @click="goToCategoryList">
              <text class="stat-number">{{ userStore.userInfo?.categoryCount || 0 }}</text>
              <text class="stat-label">分类</text>
            </view>
            <view class="stat-divider"></view>
            <view class="stat-item" @click="goToTagList">
              <text class="stat-number">{{ userStore.userInfo?.tagCount || 0 }}</text>
              <text class="stat-label">标签</text>
            </view>
          </view>
        </view>
        
        <!-- 功能菜单 -->
        <view class="menu-section">
          <view class="menu-group">
            <view class="menu-item" @click="goToStatistics">
              <view class="menu-left">
                <view class="menu-icon bg-primary">
                  <text class="icon-text">📊</text>
                </view>
                <text class="menu-text">统计分析</text>
              </view>
              <text class="arrow">›</text>
            </view>
            
            <view class="menu-item" @click="goToSearch">
              <view class="menu-left">
                <view class="menu-icon bg-warning">
                  <text class="icon-text">🔍</text>
                </view>
                <text class="menu-text">搜索日记</text>
              </view>
              <text class="arrow">›</text>
            </view>
            
            <view class="menu-item" @click="goToCalendar">
              <view class="menu-left">
                <view class="menu-icon bg-success">
                  <text class="icon-text">📅</text>
                </view>
                <text class="menu-text">日历视图</text>
              </view>
              <text class="arrow">›</text>
            </view>
            
            <view class="menu-item" @click="goToFilter">
              <view class="menu-left">
                <view class="menu-icon bg-secondary">
                  <text class="icon-text">🔍</text>
                </view>
                <text class="menu-text">日记筛选与导出</text>
              </view>
              <text class="arrow">›</text>
            </view>
            
          </view>
          
          <view class="menu-group">
            <view class="menu-item" @click="goToAbout">
              <view class="menu-left">
                <view class="menu-icon bg-default">
                  <text class="icon-text">ℹ️</text>
                </view>
                <text class="menu-text">关于我们</text>
              </view>
              <text class="arrow">›</text>
            </view>
          </view>
        </view>
        
        <!-- 主题切换 -->
        <view class="theme-section">
          <view class="theme-item">
            <view class="theme-left">
              <view class="theme-icon">
                <text class="icon-text">🌙</text>
              </view>
              <text class="theme-text">深色模式</text>
            </view>
            <switch 
              :checked="userStore.themeMode === 'dark'"
              @change="toggleTheme"
              color="#1890ff"
            />
          </view>
        </view>
        
        <!-- 退出登录 -->
        <view class="logout-section">
          <button class="logout-btn" @click="handleLogout">
            <text class="logout-icon">🚪</text>
            <text class="logout-text">退出登录</text>
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部导航栏 -->
    <TabBar :current="4" />
    
    <!-- 头像上传弹窗 -->
    <view class="modal-overlay" v-if="showAvatarModal" @click="showAvatarModal = false">
      <view class="avatar-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">更换头像</text>
          <text class="modal-close" @click="showAvatarModal = false">×</text>
        </view>
        <view class="modal-body">
          <view class="avatar-options">
            <view class="avatar-option" @click="chooseAvatar('camera')">
              <text class="option-icon">📷</text>
              <text class="option-text">拍照</text>
            </view>
            <view class="avatar-option" @click="chooseAvatar('album')">
              <text class="option-icon">🖼️</text>
              <text class="option-text">从相册选择</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { getUserProfileAPI, updateUserProfileAPI } from '@/api/user'
import { uploadAvatarAPI } from '@/api/upload'
import { getStatsOverviewAPI } from '@/api/statistics'
import { formatDate, extractResponseData } from '@/utils/index'
import TabBar from '@/components/TabBar.vue'

export default {
  name: 'ProfilePage',
  components: {
    TabBar
  },
  setup() {
    const userStore = useUserStore()
    
    return {
      userStore,
      formatDate
    }
  },
  data() {
    return {
      loading: false,
      showAvatarModal: false
    }
  },
  
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    }
  },
  onLoad() {
    this.loadUserProfile()
  },
  onShow() {
    this.loadUserProfile()
  },
  methods: {
    // 加载用户资料
    async loadUserProfile() {
      if (!this.userStore.checkLoginStatus()) return
      
      try {
        // 分别获取用户信息和统计数据，增加错误处理
        let userData = null
        let statsData = null
        
        try {
          const userRes = await getUserProfileAPI()
          userData = extractResponseData(userRes)
        } catch (userError) {
          console.error('获取用户信息失败:', userError)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
          return
        }
        
        try {
          const statsRes = await getStatsOverviewAPI()
          statsData = extractResponseData(statsRes)
        } catch (statsError) {
          console.error('获取统计数据失败:', statsError)
          // 统计数据获取失败不影响主流程，使用默认值
          statsData = {
            diaryCount: 0,
            categoryCount: 0,
            tagCount: 0
          }
        }
        
        // 确保统计数据的字段存在且为数字（处理下划线命名到驼峰命名的转换）
        const safeStatsData = {
          diaryCount: Number(statsData?.diary_count || statsData?.diaryCount) || 0,
          categoryCount: Number(statsData?.category_count || statsData?.categoryCount) || 0,
          tagCount: Number(statsData?.tag_count || statsData?.tagCount) || 0
        }
        
        // 合并统计数据到用户信息中
        const userWithStats = {
          ...userData,
          ...safeStatsData
        }
        
        this.userStore.updateUserInfo(userWithStats)
      } catch (error) {
        console.error('加载用户资料失败:', error)
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        })
      }
    },

    
    // 格式化加入日期
    formatJoinDate(dateStr) {
      if (!dateStr) return '未知'
      const date = new Date(dateStr)
      return `${date.getFullYear()}年${date.getMonth() + 1}月加入`
    },
    
    // 显示头像更换选项
    showAvatarOptions() {
      this.showAvatarModal = true
    },
    
    // 编辑个人资料
    editProfile() {
      uni.navigateTo({
        url: '/pages/profile/edit'
      })
    },
    
    // 选择头像
    chooseAvatar(sourceType) {
      const source = sourceType === 'camera' ? ['camera'] : ['album']
      
      uni.chooseImage({
        count: 1,
        sourceType: source,
        success: (res) => {
          this.uploadAvatar(res.tempFilePaths[0])
        }
      })
      
      this.showAvatarModal = false
    },
    
    // 上传头像
    async uploadAvatar(filePath) {
      if (!filePath) return
      
      try {
        uni.showLoading({ title: '上传中...' })
        
        // 上传头像
        const uploadRes = await uploadAvatarAPI(filePath)
        const uploadData = extractResponseData(uploadRes)
        
        // 更新用户信息
        const updateRes = await updateUserProfileAPI({
          avatar: uploadData.url
        })
        const updatedUser = extractResponseData(updateRes)
        
        // 更新本地用户信息
        this.userStore.updateUserInfo(updatedUser)
        
        uni.showToast({
          title: '头像更新成功',
          icon: 'success'
        })
        
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 切换主题
    toggleTheme(e) {
      const isDark = e.detail.value
      this.userStore.setThemeMode(isDark ? 'dark' : 'light')
    },
    
    // 退出登录
    async handleLogout() {
      const result = await uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        confirmText: '退出',
        confirmColor: '#ff4d4f'
      })
      
      if (!result.confirm) return
      
      try {
        await this.userStore.logout()
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
        
        // 跳转到登录页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 1000)
        
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.showToast({
          title: '退出失败',
          icon: 'none'
        })
      }
    },
    
    // 导航方法
    goToDiaryList() {
      uni.switchTab({
        url: '/pages/diary/list'
      })
    },
    
    goToCategoryList() {
      uni.switchTab({
        url: '/pages/category/list'
      })
    },
    
    goToTagList() {
      uni.navigateTo({
        url: '/pages/tag/list'
      })
    },
    
    goToStatistics() {
      uni.navigateTo({
        url: '/pages/statistics/index'
      })
    },
    
    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/index'
      })
    },
    
    goToCalendar() {
      uni.navigateTo({
        url: '/pages/diary/calendar'
      })
    },
    
    goToAbout() {
      uni.navigateTo({
        url: '/pages/profile/about'
      })
    },
    
    goToFilter() {
      uni.navigateTo({
        url: '/pages/diary/filter'
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.nav-bar.transparent {
  background: transparent;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 40rpx;
  height: 88rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.page-content {
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx);
  padding-bottom: 160rpx;
}

.profile-scroll {
  height: 100%;
}

.user-card {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 40rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-wrapper {
  position: relative;
  margin-right: 32rpx;
}

.user-avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  border: 6rpx solid #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.avatar-edit {
  position: absolute;
  bottom: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  border-radius: 24rpx;
  background-color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.edit-icon {
  color: #ffffff;
  font-size: 24rpx;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.user-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  cursor: pointer;
  transition: color 0.2s;
}

.user-name:active {
  color: #1890ff;
}

.user-email {
  font-size: 28rpx;
  color: #666666;
}

.join-date {
  font-size: 24rpx;
  color: #999999;
}

.stats-container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 32rpx 0;
  border-top: 1rpx solid #f0f0f0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  transition: transform 0.2s;
}

.stat-item:active {
  transform: scale(0.95);
}

.stat-number {
  font-size: 48rpx;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 26rpx;
  color: #666666;
}

.stat-divider {
  width: 1rpx;
  height: 80rpx;
  background-color: #f0f0f0;
}

.menu-section {
  margin: 0 40rpx;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.menu-group {
  background-color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  border-bottom: 1rpx solid #f8f8f8;
  transition: background-color 0.2s;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item:active {
  background-color: #f8f8f8;
}

.menu-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.menu-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.bg-primary {
  background-color: #1890ff;
}

.bg-success {
  background-color: #52c41a;
}

.bg-warning {
  background-color: #faad14;
}

.bg-info {
  background-color: #13c2c2;
}

.bg-secondary {
  background-color: #722ed1;
}

.bg-default {
  background-color: #666666;
}

.icon-text {
  font-size: 32rpx;
}

.menu-text {
  font-size: 32rpx;
  color: #333333;
}

.arrow {
  font-size: 32rpx;
  color: #cccccc;
}

.theme-section {
  margin: 0 40rpx 32rpx;
}

.theme-item {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx 40rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.theme-left {
  display: flex;
  align-items: center;
}

.theme-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.theme-text {
  font-size: 32rpx;
  color: #333333;
}

.logout-section {
  margin: 0 40rpx;
}

.logout-btn {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  border: none;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.logout-btn::after {
  border: none;
}

.logout-btn:active {
  background-color: #f8f8f8;
}

.logout-icon {
  font-size: 32rpx;
}

.logout-text {
  font-size: 32rpx;
  color: #ff4d4f;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-modal {
  background-color: #ffffff;
  border-radius: 24rpx;
  margin: 40rpx;
  width: calc(100% - 80rpx);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  font-size: 48rpx;
  color: #cccccc;
}

.modal-body {
  padding: 40rpx;
}

.avatar-options {
  display: flex;
  gap: 40rpx;
  justify-content: center;
}

.avatar-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
  transition: background-color 0.2s;
  min-width: 160rpx;
}

.avatar-option:active {
  background-color: #f0f0f0;
}

.option-icon {
  font-size: 64rpx;
  margin-bottom: 16rpx;
}

.option-text {
  font-size: 28rpx;
  color: #333333;
}

/* 主题适配 */
.theme-light.page-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}

.theme-dark.page-container {
  background: linear-gradient(135deg, #2d2d30 0%, #404040 100%) !important;
}

.theme-dark .nav-title {
  color: #e8e8e8;
}

.theme-dark .user-card,
.theme-dark .menu-item,
.theme-dark .theme-item,
.theme-dark .logout-btn {
  background-color: #252526;
}

.theme-dark .user-name {
  color: #e8e8e8;
}

.theme-dark .user-name:active {
  color: #1890ff;
}

.theme-dark .user-email,
.theme-dark .join-date,
.theme-dark .stat-label,
.theme-dark .menu-text,
.theme-dark .theme-text {
  color: #b3b3b3;
}

.theme-dark .stat-number {
  color: #e8e8e8;
}

.theme-dark .stat-divider {
  background-color: #404040;
}

.theme-dark .theme-icon {
  background-color: #404040;
}

.theme-dark .arrow {
  color: #8c8c8c;
}

.theme-dark .avatar-modal {
  background-color: #252526;
}

.theme-dark .modal-title {
  color: #e8e8e8;
}

.theme-dark .modal-header {
  border-bottom-color: #404040;
}

.theme-dark .modal-close {
  color: #8c8c8c;
}

.theme-dark .avatar-option {
  background-color: #404040;
}

.theme-dark .option-text {
  color: #e8e8e8;
}
</style> 